package com.offcn.dao.Impl;

import com.offcn.dao.BaseDao;
import com.offcn.dao.CourseDao;
import com.offcn.entity.Course;
import com.offcn.utils.PageTool;

import java.util.List;

public class CourseDaoImpl extends BaseDao<Course> implements CourseDao {
    @Override
    public int getTotalCount(String search) {
        String sql = "select count(*) from course";
        if (search != null && !"".equals(search)) {
            sql += " where courseName like '%" + search + "%'";
        }
        long count = (long) singleData(sql);
        return (int) count;
    }

    @Override
    public List<Course> findAllCourse(PageTool pageTool, String search) {
        String sql = "select * from course";
        if (search != null && !"".equals(search)) {
            sql += " where courseName like '%" + search + "%'";
        }
        sql += " limit ?,?";
        return moreLine(sql, Course.class, pageTool.getStartIndex(), pageTool.getPageSize());
    }

    @Override
    public int addCourse(Course course) {
        String sql = "insert into course values(null,?,?,?,?,?,?,?,now())";
        String imgName = course.getCourseImage().substring(course.getCourseImage().lastIndexOf("/") + 1);
        String videoName = course.getCourseVideo().substring(course.getCourseVideo().lastIndexOf("/") + 1);
        return dml(sql, course.getCourseName(), course.getDescs(), course.getCourseType(),
                imgName, videoName, course.getCoursePrice(), course.getStatus());
    }

    @Override
    public int delAll(String arr) {
        String sql = "delete from course where cid in " + arr;
        return dml(sql);
    }

    @Override
    public int updateCourse(Course course) {
        String sql = "update course set courseName = ?, descs = ?, courseType = ?, courseImage = ?," +
                " courseVideo = ?, coursePrice = ?, status = ?, createTime = ? where cid = ?";
        return dml(sql, course.getCourseName(), course.getDescs(), course.getCourseType(), course.getCourseImage()
                , course.getCourseVideo(), course.getCoursePrice(), course.getStatus(), course.getCreateTime(), course.getCid());
    }

    @Override
    public Course findByCid(int cid) {
        String sql = "select * from course where cid = " + cid;
        return singleLine(sql, Course.class);
    }

    @Override
    public List<Course> findCourse(String uid, String cid) {
        String sql = "select * from course where cid not in(" +
                "select cid from course_user where uid = ? and cid != ?);";
        return moreLine(sql, Course.class, uid, cid);
    }

    @Override
    public List<Course> findByCourseType(String coursetype, int num) {
        String sql = "select * from course where courseType = ?";
        if (num > 0) {
            sql += " limit 0,"+num;
        }
        return moreLine(sql, Course.class, Integer.parseInt(coursetype));
    }
}
